<template>
  <view class="custom-scroll-view" id="custom-scroll-view"
    :style="{ height: contentHeight ? contentHeight + 'px' : 'auto' }">
		<!-- 				empty: empty -->
    <mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" @scroll="scrollCallback"
			:up="{
        noMoreSize: noMoreSize,
        onScroll: true,
        auto: scrollAuto,
      }" :down="{
        auto: scrollAuto
      }" :fixed="false" :height="slots.footer || hasCustomHeight ? contentHeight - 56 + 'px' : contentHeight + 'px'">
      <slot></slot>
    </mescroll-uni>
    <view class="footer contentFilter" :class="[
      !isEnd || (isEnd && slots.footer)
        ? 'contentFilter-in'
        : 'contentFilter-out',
      slots.footer ? 'contentFilter-bg' : 'contentFilter-height'
    ]">
      <slot name="footer"></slot>
    </view>
  </view>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  useSlots,
  getCurrentInstance,
  nextTick,
  computed,
  watch,
  defineExpose
} from 'vue'
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js'
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import { getUrl } from '@/utils/imagePlugin'
const { mescrollInit, getMescroll, downCallback } = useMescroll(
  onPageScroll,
  onReachBottom
)
const slots: { list?(_: {}): any; footer?(_: {}): any } = useSlots()
const _this: any = getCurrentInstance()
const totalSize = ref(100)
const props = defineProps({
	isRevenue: {
	  type: Boolean,
	  default: false
	},
	hasCustomHeight: {
	  type: Boolean,
	  default: false
	},
	isPropsChange: {
	  type: Boolean,
	  default: true
	},
  pageSize:{
    type: String,
	  default: '10'
  },
	noMoreSize: {
	  type: Number,
	  default: 5
	},
  scrollAuto: {
    type: Boolean,
    default: true
  },
  fixedheight: {//指定高度（弹窗）
    type: Number,
    default: 0
  },
  initParam: {
    type: Object,
    default: () => {
      return {
        api: null, //api接口
        param: {}, //参数
        _props: '' //数组的key
      }
    }
  }
})
const emit = defineEmits<{
  (e: 'sendData', event: any): void
  (e: 'sendMore', event: any): void
  (e: 'inited', event?: any): void
}>()
const list = ref([])
const contentHeight = ref(0)
const isEnd = ref(false) //是否触底
const isLastData = ref(false)

//可通过ref重新计算高度
const resize = () => {
  init()
}
const scrollCallback = (mescroll: any) => {
  if (isLastData.value) {
    const listHeight = mescroll.scrollHeight;
    const scrollTop = mescroll.scrollTop;
    isEnd.value = Math.round(listHeight - scrollTop - contentHeight.value) < 20
  }
}
//
const upCallback = (mescroll: any) => {
  console.log('props.initParam.api',props.initParam.api)
  if (!props.initParam.api) {
    // mescroll.endErr()
    mescroll.lockDownScroll()
    mescroll.lockUpScroll()
    mescroll.endBySize(1, 1)
    return
  } else {
    mescroll.lockDownScroll(false)
    mescroll.lockUpScroll(false)
  }
  if (mescroll.num == 1) {
    list.value = []
  }
	// console.log(mescroll.num,list.value)

	// console.log(props)
  if (props.initParam.api && typeof props.initParam.api === 'function') {
    props.initParam.api({
        ...props.initParam.param,
        pageNum: mescroll.num,
        pageSize: Number(props.pageSize)>0?props.pageSize : mescroll.size
      })
      .then((res: any) => {
        const curPageData = res.rows || []
				if(props.isRevenue){
					if(list.value.length > 0 && (list.value[list.value.length - 1].yearMonth === curPageData[0].yearMonth)){
						list.value[list.value.length - 1].profitRecord.concat(curPageData[0].profitRecord)
					} else {
						list.value = list.value.concat(curPageData)
					}
					const moredata = {
					 
					}
					emit('sendMore', moredata)
					emit('sendData', list.value)
					totalSize.value = Number(res.total)
					let curPageDataList = []
					for(let i = 0; i < curPageData.length; i++){
						curPageDataList = curPageDataList.concat(curPageData[i].profitRecord)
					}
					mescroll.endBySize(curPageDataList.length, totalSize.value)
					isEnd.value = false
					if (res.total === 0) {
						mescroll.showEmpty()
						isEnd.value = true
					}
				} else {
					list.value = list.value.concat(curPageData)
					const moredata = {
					 
					}
					emit('sendMore', moredata)
					emit('sendData', list.value)
					totalSize.value = Number(res.total)
					mescroll.endBySize(curPageData.length, totalSize.value)
					isLastData.value = list.value.length === totalSize.value
					isEnd.value = false
					if (res.total === 0) {
						mescroll.showEmpty()
						isEnd.value = true
					}
				}
        
      })
      .catch((err: any) => {
        console.log(err, '分页错误===err')
        emit('sendData', [])
        mescroll.endErr()
        mescroll.showEmpty()
      })
  } else {
    mescroll.showEmpty()
    mescroll.endErr()
    emit('sendData', [])
  }
}

const init = () => {
  setTimeout(() => {
    uni.getSystemInfo({
      success: (res) => {
        const query = uni.createSelectorQuery().in(_this) // 确保在页面上下文中调用
        query
          .select('#custom-scroll-view') // 添加 # 号以正确匹配 ID 选择器
          .boundingClientRect((data) => {
            console.log(res.windowHeight, data.top, '===========custom-scroll-view')
            if(props.fixedheight>0){
              contentHeight.value = props.fixedheight
            }else{
              contentHeight.value = res.windowHeight - data.top
            }
          })
          .exec()
      },
      fail: (err) => {
        console.error('获取系统信息失败:', err)
      }
    })
  }, 10)
}

watch(
  () => props.initParam,
  (val) => {
    if (val) {
      console.log('downCallback')
			if(props.isPropsChange){
				downCallback()
			}
    }
  },
  {
    // immediate: true,
    deep: true
  }
)

defineExpose({ resize, downCallback })
onMounted(() => {
  init()
  emit('inited')
})
</script>

<style lang="scss" scoped>
::-webkit-scrollbar {
  display: none;
}

.pb-10 {
  padding-bottom: 10rpx;
}

.pb-168 {
  padding-bottom: 168rpx;
}

.custom-scroll-view {
  transform: rotate3d(0, 0, 0);
  overflow: scroll;

}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding-bottom: env(safe-area-inset-bottom, 0px);
  box-sizing: border-box;
  z-index: 20;
}

.contentFilter-bg {
  // &::before {
  //   background: linear-gradient(to bottom, rgba(255, 255, 255, 0), #f3ece4);
  //   width: 100%;
  //   content: '';
  //   position: absolute;
  //   top: -80rpx;
  //   height: 140rpx;
  //   z-index: -1;
  // }
}

.contentFilter {
  // background: linear-gradient(to bottom, rgba(255, 255, 255, 0), #f3ece4);
  // // pointer-events: none;
  // transition: opacity 0.3s linear;
}

.contentFilter-height {
  height: 168rpx;
}

.contentFilter-in {
  opacity: 1;
}

.contentFilter-out {
  opacity: 0;
}
</style>
